package com.xique.park.command.handler;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.park.api.IParkIpcCommandApi;
import com.xique.park.bean.domain.ParkCar;
import com.xique.park.command.handler.base.BaseCommand;
import com.xique.park.constant.CommandConstant;
import com.xique.park.constant.ParkApiName;
import com.xique.park.service.service.IParkCarService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 下载车辆信息
 *
 * @author WLD
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class DownCarCommandHandler extends BaseCommand {

    private final IParkCarService parkCarService;

    private final IParkIpcCommandApi parkIpcCommandApi;

    @Override
    public String getServiceName() {
        return ParkApiName.COMMAND_CAR_DOWNLOAD;
    }

    @Override
    public String getVersion() {
        return ParkApiName.VER_2_0;
    }

    @Override
    @SuppressWarnings("unchecked")
    public AjaxResult issue(Long parkId, Long laneId, String mngTypeIds, String sn,
                            MultipartFile file, String fileName, String cmd) {
        checkParkId(parkId);
        checkSn(sn);

        ParkCar parkCar = new ParkCar();
        parkCar.setParkId(parkId);
        List<ParkCar> carList = parkCarService.selectParkCarList(parkCar);
        if (CollUtil.isNotEmpty(carList)) {
            List<List<ParkCar>> newCarLists = CollUtil.split(carList, 100);
            Map<String, Object> params = null;
            AjaxResult issueResult = null;
            for (List<ParkCar> parkCarList : newCarLists) {
                JSONObject baseObj = getBaseObj(sn, getServiceName(), getVersion());
                JSONObject dataObj = new JSONObject();
                dataObj.put(CommandConstant.LIST, parkCarList);
                List<Long> recIdList = parkCarList.stream().map(ParkCar::getId).collect(Collectors.toList());
                dataObj.put(CommandConstant.REC_IDS, recIdList);
                baseObj.put(CommandConstant.DATA, dataObj);

                params = JSON.toJavaObject(baseObj, Map.class);
                issueResult = parkIpcCommandApi.issue(params);

                log.info("[停车系统]下载车辆信息命令下发，服务名：{}，版本号：{}，车场ID：{}，设备编号：{}，下发参数：{}，下发结果：{}",
                        getServiceName(), getVersion(), parkId, sn, params, issueResult);
            }

            updateCommonInfo(cmd, params, Objects.requireNonNull(issueResult));

            return AjaxResult.success("下载车辆信息命令下发");
        } else {
            return AjaxResult.success("该车场未添加车辆");
        }
    }

}
